package DataStrue.PriorityQueue;


import java.util.PriorityQueue;

public class TextHeap {
  public int[] elem;
  public int usedSize;
  public TextHeap(){
      elem = new int[10];
  }

  public void initHeap(int[] array){
      for(int i = 0; i < array.length; i++){
          elem[i]  = array[i];
          usedSize++;
      }
  }

  public void createHeap(){
      for(int parent = (usedSize -1-1) /2; parent>=0; parent--){
          shitDown(parent);
      }
  }

  public void shitDown(int parent){
      int child = (parent *2) +1;
      while(child < usedSize){
          if((child +1) < usedSize && elem[child]  < elem[child +1]){
              child++;
          }
          if(elem[child] > elem[parent]){
              swap(child, parent);
              parent = child;
              child = (parent *2) + 1;

          }else{
              break;
          }
      }
  }


  public void swap(int child, int parent){
      int tmep = elem[parent];
      elem[parent] = elem[child];
      elem[child] = tmep;
  }

  public void shitUp(int child){
      int parent = (child -1)/2;
      while(child > 0){
          if(elem[child] < elem[parent]){
              break;
          }else{
              swap(parent,child);
              child = parent;
              parent = (child -1) /2;
          }
      }
  }



  public int[] smallK(int[] arr, int k){
      if(k < 0 || k > arr.length || arr == null){
          return null;
      }

      PriorityQueue<Integer> queue = new PriorityQueue<>();
      for(int i = 0 ;i < arr.length; i++){
          queue.offer(arr[i]);
      }

      int[] result = new int[k];
      for(int i = 0; i <  k; i++){
          result[i] = queue.poll();
      }
      return result;
  }









        public int[] smallestK(int[] arr, int k) {
            // 参数检测
            if (arr == null || k <= 0 || k > arr.length) {
                return null;
            }

            // 创建一个优先级队列（小顶堆）
            PriorityQueue<Integer> pq = new PriorityQueue<>();

            // 将所有元素加入堆
            for (int num : arr) {
                pq.offer(num);
            }

            // 取出堆中前k个元素
            int[] result = new int[k];
            for (int i = 0; i < k; i++) {
                result[i] = pq.poll();
            }

            return result;
        }


}